<?php

namespace app\admin\controller;

use think\Db;
use think\facade\Request;
use nsCms\Form;

class Base extends Common
{
    protected $dao, $fields;
    
    public function initialize()
    {
        parent::initialize();
        $this->moduleid = $this->mod[MODULE_NAME];
        $this->dao = db(MODULE_NAME);
        $fields = cache($this->moduleid . '_Field');
        foreach ($fields as $key => $res) {
            $res['setup'] = string2array($res['setup']);
            $this->fields[$key] = $res;
        }
        unset($fields);
        unset($res);
        $this->assign('fields', $this->fields);
    }
    
    public function index()
    {
        if (Request::isAjax()) {
            $model = db(MODULE_NAME);
            $map = [];
            //分类
            $cinfo = ['catdir' => MODULE_NAME, 'is_show' => 1];
            $catid = input('catid/i', 0);
            if (!empty($catid)) {
                $cinfo = db('category')->where(['id' => $catid])->field('catdir,is_show')->find();
                $catids = db('category')->where(['parentid' => $catid])->column('id');
                if ($catids) {
                    $catid = input('post.catid') . ',' . implode(',', $catids);
                } else {
                    $catid = input('post.catid');
                }
            }
            
            //关键字
            $keyword = input('key');
            if (!empty($keyword)) {
                $map[] = ['title', 'like', '%' . $keyword . '%'];
            }
            
            //数据字段
            $Fields = Db::getConnection()->getFields($this->prefix . MODULE_NAME);
            foreach ($Fields as $k => $v) {
                $field[$k] = $k;
            }
            //存在分类
            if (in_array('catid', $field)) {
                $map[] = ['catid', 'in', $catid];
            }
            $list = $model->where($map)
                ->order('sort asc,sort asc,id asc')
                ->paginate(getPage())
                ->toArray();
            $lists = $list['data'];
            foreach ($lists as $k => $v) {
                $lists[$k]['create_time'] = date('Y-m-d H:i:s', @$v['create_time']);
                $lists[$k]['catdir'] = $cinfo['catdir'];
                $lists[$k]['is_show'] = $cinfo['is_show'];
                $lists[$k]['url'] = url('home/' . $cinfo['catdir'] . '/info', ['id' => $v['id'], 'catId' => @$v['catid']]);
            }
            
            $rsult['code'] = 0;
            $rsult['msg'] = "获取成功";
            $rsult['data'] = $lists;
            $rsult['count'] = $list['total'];
            $rsult['rel'] = 1;
            return $rsult;
        } else {
            return $this->fetch('content/index');
        }
    }
    
    public function edit()
    {
        $id = input('id');
        if (empty($id)) {
            $form = new Form();
            $this->assign('form', $form);
            $this->assign('title', '添加内容');
            return $this->fetch('content/edit');
        } else {
            $request = Request::instance();
            $controllerName = $request->controller();
            if ($controllerName == 'Page') {
                $p = $this->dao->where('id', $id)->find();
                if (empty($p)) {
                    $data['id'] = $id;
                    $data['title'] = $this->categorys[$id]['catname'];
                    $data['keywords'] = $this->categorys[$id]['keywords'];
                    $this->dao->insert($data);
                }
            }
            $info = $this->dao->where('id', $id)->find();
            $form = new Form($info);
            $returnData['vo'] = $info;
            $returnData['form'] = $form;
            $this->assign('info', $info);
            $this->assign('form', $form);
            $this->assign('title', '编辑内容');
            return $this->fetch('content/edit');
        }
    }
    
    function doEdit()
    {
        $model = $this->dao;
        $fields = $this->fields;
        $data = $this->checkfield($fields, Request::except('file'));
        if (isset($data['code'])) {
            return ['code' => 0, 'msg' => $data['msg']];
        }
        if (isset($fields['update_time'])) {
            $data['userid'] = session('admin_id');
        }
        
        if (isset($fields['update_time'])) {
            $data['update_time'] = time();
        }
        
        $title_style = '';
        if (isset($data['style_color'])) {
            $title_style .= 'color:' . $data['style_color'] . ';';
            unset($data['style_color']);
        } else {
            $title_style .= 'color:#222;';
        }
        if (isset($data['style_bold'])) {
            $title_style .= 'font-weight:' . $data['style_bold'] . ';';
            unset($data['style_bold']);
        } else {
            $title_style .= 'font-weight:normal;';
        }
        if ($fields['title']['setup']['style'] == 1) {
            $data['title_style'] = $title_style;
        }
        if (MODULE_NAME != 'Page') {
            $data['update_time'] = time();
        }
        unset($data['aid']);
        unset($data['pics_name']);
        //编辑多图和多文件
        foreach ($fields as $k => $v) {
            if ($v['type'] == 'files') {
                if (!$data[$k]) {
                    $data[$k] = '';
                }
                $data[$v['field']] = $data['images'];
            }
            if ($v['type'] == 'images') {
                if (!isset($data[$k])) {
                    $data[$k] = '';
                }
                if ($data[$k]) {
                    $data[$v['field']] = implode(';', $data[$k]);
                }
            }
        }
        if (isset_full($data, 'id')) {
            $id = $model->strict(false)->update($data);
        } else {
            $id = $model->insertGetId($data);
        }
        if ($id) {
            if (MODULE_NAME == 'Page') {
                $result['url'] = url("admin/category/index");
            } else {
                $result['url'] = url("admin/" . MODULE_NAME . "/index", ['catid' => @$data['catid']]);
            }
            $result['msg'] = '操作成功!';
            $result['code'] = 1;
            return $result;
        } else {
            $result['msg'] = '操作失败!';
            $result['code'] = 0;
            return $result;
        }
    }
    
    function checkfield($fields, $post)
    {
        foreach ($post as $key => $val) {
            if (isset($fields[$key])) {
                $setup = $fields[$key]['setup'];
                if (!empty($fields[$key]['required']) && empty($post[$key])) {
                    $result['msg'] = $fields[$key]['errormsg'] ? $fields[$key]['errormsg'] : '缺少必要参数！';
                    $result['code'] = 0;
                    return $result;
                }
                if (isset($setup['multiple'])) {
                    if (is_array($post[$key])) {
                        $post[$key] = implode(',', $post[$key]);
                    }
                }
                if (isset($setup['inputtype'])) {
                    if ($setup['inputtype'] == 'checkbox') {
                        $post[$key] = implode(',', $post[$key]);
                    }
                }
                if (isset($setup['fieldtype'])) {
                    if ($fields[$key]['type'] == 'checkbox') {
                        $post[$key] = implode(',', $post[$key]);
                    }
                }
                if ($fields[$key]['type'] == 'datetime') {
                    $post[$key] = strtotime($post[$key]);
                } elseif ($fields[$key]['type'] == 'textarea') {
                    $post[$key] = addslashes($post[$key]);
                } elseif ($fields[$key]['type'] == 'linkage') {
                    if ($post[$key][0]) {
                        $post[$key] = implode(',', $post[$key]);
                    } else {
                        unset($post[$key]);
                    }
                } elseif ($fields[$key]['type'] == 'editor') {
                    if (isset($post['add_description']) && $post['description'] == '' && isset($post['content'])) {
                        $content = stripslashes($post['content']);
                        $description_length = intval($post['description_length']);
                        $post['description'] = str_cut(str_replace(["\r\n", "\t", '[page]', '[/page]', '&ldquo;', '&rdquo;'], '', strip_tags($content)), $description_length);
                        $post['description'] = addslashes($post['description']);
                    }
                    if (isset($post['auto_thumb']) && $post['thumb'] == '' && isset($post['content'])) {
                        $content = $content ? $content : stripslashes($post['content']);
                        $auto_thumb_no = intval($post['auto_thumb_no']) * 3;
                        if (preg_match_all("/(src)=([\"|']?)([^ \"'>]+\.(gif|jpg|jpeg|bmp|png))\\2/i", $content, $matches)) {
                            $post['thumb'] = $matches[$auto_thumb_no][0];
                        }
                    }
                }
            }
        }
        return $post;
    }
    
    public function listDel()
    {
        $id = input('post.id');
        $model = $this->dao;
        $model->where(['id' => $id])->delete();//转入回收站
        return ['code' => 1, 'msg' => '删除成功！'];
    }
    
    public function delAll()
    {
        $map[] = ['id', 'in', input('post.ids/a')];
        $model = $this->dao;
        $model->where($map)->delete();
        $result['code'] = 1;
        $result['msg'] = '删除成功！';
        $result['url'] = url('index', ['catid' => input('post.catid')]);
        return $result;
    }
    
    public function listorder()
    {
        $model = $this->dao;
        $catid = input('catid',0);
        $data = input('post.');
        unset($data['catid']);
        $model->update($data);
        $result = ['msg' => '排序成功！', 'url' => url('index', ['catid' => $catid]), 'code' => 1];
        return $result;
    }
    
    public function delImg()
    {
        if (!input('post.url')) {
            return ['code' => 0, '请指定要删除的图片资源'];
        }
        $file = ROOT_PATH . __PUBLIC__ . input('post.url');
        if (file_exists($file) && trim(input('post.url')) != '') {
            is_dir($file) ? dir_delete($file) : unlink($file);
        }
        if (input('post.id')) {
            $picurl = input('post.picurl');
            $picurlArr = explode(':', $picurl);
            $pics = substr(implode(":::", $picurlArr), 0, -3);
            $model = $this->dao;
            $map['id'] = input('post.id');
            $model->where($map)->update(['pics' => $pics]);
        }
        $result['msg'] = '删除成功!';
        $result['code'] = 1;
        return $result;
    }
    
    public function getRegion()
    {
        $Region = db("area");
        $map['pid'] = input("pid");
        $list = $Region->where($map)->select();
        return $list;
    }
}